package com.caiyi.financial.nirvana.sms.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.caiyi.financial.nirvana.sms.entity.SmsReceiveMessage;
import com.caiyi.financial.nirvana.sms.entity.SmsUser;
import com.caiyi.financial.nirvana.sms.jedis.JedisKey;
import com.caiyi.financial.nirvana.sms.jedis.JedisService;
import com.caiyi.financial.nirvana.sms.querybean.QueryReceiveMessage;
import com.caiyi.financial.nirvana.sms.service.SmsReceiveMessageService;
import com.caiyi.financial.nirvana.sms.util.CommUtil;
import com.caiyi.financial.nirvana.sms.util.HttpClientUtil;
import com.youyu.common.api.Result;
import com.caiyi.financial.nirvana.sms.util.SignUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Api(description = "上行短信管理接口")
@CrossOrigin
@RestController
@RequestMapping("sms/admin/receivemessage")
public class ReceiveMessageController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SmsReceiveMessageService receiveMessageService;

    @ApiOperation(value = "根据条件查找上行短信详情", notes = "根据条件查找上行短信描述")
    @ApiImplicitParam(name = "bean", value = "查找上行短信实体", required = true, dataType = "QueryReceiveMessage")
    @PostMapping("/getReceiveMessageList")
    public Result getReceiveMessageList(@RequestBody QueryReceiveMessage bean) {
        return Result.ok(receiveMessageService.getReceiveMessageListByParams(bean));
    }

    @ApiOperation(value = "手动推送上行短信到客户")
    @ApiImplicitParam(name = "ids", value = "上行短信id", required = true, dataType = "String", paramType = "query")
    @PostMapping("/pushReceiveMessage")
    public Result pushReceiveMessage(@RequestParam String ids) {
        Result Result = new Result();
        List<SmsReceiveMessage> smsReceiveMessageList = receiveMessageService.getReceiveMsgByIds(ids);
        JSONArray result = new JSONArray();
        for (SmsReceiveMessage item : smsReceiveMessageList) {
            String message = this.pushMessage(item);
            JSONObject obj = new JSONObject();
            obj.put("id", item.getId());
            obj.put("desc", StringUtils.isEmpty(message) ? "接口返回NULL" : message);
            result.add(obj);
        }
        Result.setData(result);
        return Result;
    }

    /**
     * 推送消息到客户
     *
     * @param smsReceiveMessage message
     * @return 消息
     */
    private String pushMessage(SmsReceiveMessage smsReceiveMessage) {
        try {
            if (StringUtils.isBlank(smsReceiveMessage.getAccount())) {
                logger.info("账户为空.");
                return "此消息账户为空,无法推送.";
            }
            //查询Redis获取客户推送地址
            String key = String.format(JedisKey.SMS_USER, smsReceiveMessage.getAccount());
            String jsonUser = JedisService.get(key);
            SmsUser user = JSON.parseObject(jsonUser, SmsUser.class);
            String receiveUrl = user.getReceiveUrl();
            if (StringUtils.isBlank(receiveUrl)) {
                logger.info("账户：{} - 未配置上行短信推送地址。", smsReceiveMessage.getAccount());
                return "此账户未配置上行短信推送地址.";
            }
            //推送参数
            Map<String, String> pushMap = new HashMap<>();
            pushMap.put("account", smsReceiveMessage.getAccount());
            pushMap.put("messageId", smsReceiveMessage.getMessageId());
            pushMap.put("phone", smsReceiveMessage.getPhone());
            pushMap.put("content", smsReceiveMessage.getContent());
            pushMap.put("accessNumber", smsReceiveMessage.getAccessNumber());
            pushMap.put("receiveTime", CommUtil.YYYY_MM_DD_HH_MM_SS.get().format(smsReceiveMessage.getCreateTime()));
            String sign = SignUtil.createSign(pushMap, user.getPassword());
            pushMap.put("sign", sign);
            String response = HttpClientUtil.doPost(receiveUrl, JSON.toJSONString(pushMap));
            logger.info("{}手动推送，内容：{}，推送结果：{}", smsReceiveMessage.getAccount(), smsReceiveMessage.getContent(), response);
            return response;
        } catch (Exception e) {
            logger.error("pushReceiveMessage error", e);
            return smsReceiveMessage + " 异常: " + e.getMessage();
        }
    }
}
